from flask import Blueprint, request, jsonify, session
from models.ai_config import AIConfig
from models.style_template import StyleTemplate
from models.image_task import ImageTask
from models.user import User
from app import db
from datetime import datetime, timedelta

admin_bp = Blueprint('admin', __name__)

def require_admin():
    """管理员权限验证装饰器的简单实现"""
    user_id = session.get('user_id')
    if not user_id:
        return jsonify({'error': '请先登录'}), 401
    
    # 这里简化处理，实际项目中需要更严格的权限验证
    # 可以在User模型中添加is_admin字段
    return None

@admin_bp.route('/ai-configs', methods=['GET'])
def get_ai_configs():
    """获取AI配置列表"""
    auth_error = require_admin()
    if auth_error:
        return auth_error
    
    try:
        configs = AIConfig.query.all()
        return jsonify({
            'configs': [config.to_dict() for config in configs]
        })
    except Exception as e:
        return jsonify({'error': f'获取配置失败: {str(e)}'}), 500

@admin_bp.route('/ai-configs', methods=['POST'])
def create_ai_config():
    """创建AI配置"""
    auth_error = require_admin()
    if auth_error:
        return auth_error
    
    try:
        data = request.get_json()
        
        config = AIConfig(
            name=data['name'],
            provider=data['provider'],
            api_endpoint=data['api_endpoint'],
            api_key=data['api_key'],
            api_secret=data.get('api_secret'),
            model_name=data['model_name'],
            model_version=data.get('model_version'),
            default_width=data.get('default_width', 512),
            default_height=data.get('default_height', 512),
            default_steps=data.get('default_steps', 20),
            default_cfg_scale=data.get('default_cfg_scale', 7.0),
            max_width=data.get('max_width', 1024),
            max_height=data.get('max_height', 1024),
            max_steps=data.get('max_steps', 50),
            cost_per_request=data.get('cost_per_request', 0.0),
            monthly_quota=data.get('monthly_quota', 1000),
            priority=data.get('priority', 1),
            is_active=data.get('is_active', True),
            is_default=data.get('is_default', False)
        )
        
        # 如果设为默认，取消其他默认配置
        if config.is_default:
            AIConfig.query.filter_by(is_default=True).update({'is_default': False})
        
        db.session.add(config)
        db.session.commit()
        
        return jsonify({
            'message': 'AI配置创建成功',
            'config': config.to_dict()
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': f'创建配置失败: {str(e)}'}), 500

@admin_bp.route('/ai-configs/<int:config_id>', methods=['PUT'])
def update_ai_config(config_id):
    """更新AI配置"""
    auth_error = require_admin()
    if auth_error:
        return auth_error
    
    try:
        config = AIConfig.query.get(config_id)
        if not config:
            return jsonify({'error': '配置不存在'}), 404
        
        data = request.get_json()
        
        # 更新字段
        for field in ['name', 'provider', 'api_endpoint', 'api_key', 'api_secret', 
                     'model_name', 'model_version', 'default_width', 'default_height',
                     'default_steps', 'default_cfg_scale', 'max_width', 'max_height',
                     'max_steps', 'cost_per_request', 'monthly_quota', 'priority',
                     'is_active', 'is_default']:
            if field in data:
                setattr(config, field, data[field])
        
        # 如果设为默认，取消其他默认配置
        if data.get('is_default'):
            AIConfig.query.filter(AIConfig.id != config_id, AIConfig.is_default == True).update({'is_default': False})
        
        db.session.commit()
        
        return jsonify({
            'message': 'AI配置更新成功',
            'config': config.to_dict()
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': f'更新配置失败: {str(e)}'}), 500

@admin_bp.route('/ai-configs/<int:config_id>', methods=['DELETE'])
def delete_ai_config(config_id):
    """删除AI配置"""
    auth_error = require_admin()
    if auth_error:
        return auth_error
    
    try:
        config = AIConfig.query.get(config_id)
        if not config:
            return jsonify({'error': '配置不存在'}), 404
        
        db.session.delete(config)
        db.session.commit()
        
        return jsonify({'message': 'AI配置删除成功'})
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': f'删除配置失败: {str(e)}'}), 500

@admin_bp.route('/statistics', methods=['GET'])
def get_statistics():
    """获取统计数据"""
    auth_error = require_admin()
    if auth_error:
        return auth_error
    
    try:
        # 用户统计
        total_users = User.query.count()
        today = datetime.now().date()
        new_users_today = User.query.filter(
            db.func.date(User.created_at) == today
        ).count()
        
        # 任务统计
        total_tasks = ImageTask.query.count()
        completed_tasks = ImageTask.query.filter_by(status='completed').count()
        failed_tasks = ImageTask.query.filter_by(status='failed').count()
        
        # 今日任务
        tasks_today = ImageTask.query.filter(
            db.func.date(ImageTask.created_at) == today
        ).count()
        
        # 热门风格
        popular_styles = db.session.query(
            StyleTemplate.name, 
            StyleTemplate.usage_count
        ).order_by(StyleTemplate.usage_count.desc()).limit(5).all()
        
        return jsonify({
            'users': {
                'total': total_users,
                'new_today': new_users_today
            },
            'tasks': {
                'total': total_tasks,
                'completed': completed_tasks,
                'failed': failed_tasks,
                'today': tasks_today,
                'success_rate': round(completed_tasks / total_tasks * 100, 2) if total_tasks > 0 else 0
            },
            'popular_styles': [
                {'name': style[0], 'count': style[1]} 
                for style in popular_styles
            ]
        })
        
    except Exception as e:
        return jsonify({'error': f'获取统计失败: {str(e)}'}), 500